package com.example.pingze.filter;

import com.alibaba.fastjson.JSONObject;
import com.example.pingze.entity.UserLoginDetails;
import com.example.pingze.utils.JwtUtil;
import com.example.pingze.utils.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)) {
            //没有token 放行
            filterChain.doFilter(request,response);
            //如果不return 在后面还会继续执行后续代码
            return;
        }
        // 解析token~token不为空
        String userId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token非法");
        }
        //从redis中获取用户信息
        String redisKey = "userLogin:" + userId;
        UserLoginDetails userLoginDetails = redisCache.getCacheObject(redisKey);

        if(Objects.isNull(userLoginDetails)) {
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder,必须要用三个参数构造方法（设置已认证标志位）
        // 获取权限信息封装到Authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userLoginDetails,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //执行完毕~放行
        filterChain.doFilter(request, response);
    }
}
